/** * Copyright (c) 2016-2019 人人开源 All rights reserved. */

package com.joinval.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joinval.common.exception.JoinvalException;
import com.joinval.common.utils.PageUtils;
import com.joinval.modules.sys.dao.SysRoleDao;
import com.joinval.modules.sys.entity.SysRoleEntity;
import com.joinval.modules.sys.service.SysRoleMenuService;
import com.joinval.modules.sys.service.SysRoleService;
import com.joinval.modules.sys.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 角色
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
	@Autowired
	private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRoleEntity role) {
        role.setCreateTime(new Date());
		SysRoleEntity roleOld = getOne(new QueryWrapper<SysRoleEntity>().lambda().eq(SysRoleEntity::getRoleName, role.getRoleName()));
		if(roleOld != null){
			throw new JoinvalException("该角色名已存在！");
		}
		this.save(role);
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRoleEntity role) {
        this.updateById(role);
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        //删除角色
        this.removeByIds(Arrays.asList(roleIds));

        //删除角色与菜单关联
        sysRoleMenuService.deleteBatch(roleIds);

        //删除角色与用户关联
        sysUserRoleService.deleteBatch(roleIds);
    }


	@Override
	public PageUtils list(Page page, String roleName) {
		Page<Map<String, Object>> list = baseMapper.list(page, roleName);
		return PageUtils.parseResult(list);
	}

	@Override
	public Map<String, Object> info(Long roleId) {
		Map<String, Object> userInfo = baseMapper.info(roleId);
        List<Long> menuIds = sysRoleMenuService.queryMenuIdList(roleId);
        userInfo.put("menuIds",menuIds);
        return userInfo;
	}

    @Override
    public List<Map<String, Object>> menu() {
        return baseMapper.menu();
    }

}
